<template>
  <div class="article-page">
    <nav class="my-nav van-hairline--bottom">
      <a
        @click="hChange('weight_desc')"
        :class="{ active : sorter === 'weight_desc' }"
        href="javascript:;">
        推荐
      </a>
      <a
        @click="hChange(null)"
        :class="{ active : sorter === null }"
        href="javascript:;">
        最新
      </a>
      <div class="logo">
        <img src="@/assets/20201125103341.png" alt="">
      </div>
    </nav>
    <!-- 下滑到底部自动加载新内容 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <ArticleItem v-for="item in list" :key="item.id" :item="item"></ArticleItem>
    </van-list>
  </div>
</template>

<script>
import { getArticle } from '@/api/article'

export default {
  name: 'ArticlePage',
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      current: 1,
      sorter: 'weight_desc'
    }
  },
  methods: {
    async onLoad () {
      // 1.load事件在页面滑动到底部时自动触发
      // 2.触发时会自动将loading改为true，此时我们可以去发请求
      // 3.请求到数据后，将loading手动改为false
      const res = await getArticle({
        current: this.current, // 当前页数
        pageSize: 10, // 每页获取多少条
        sorter: this.sorter
      })
      this.list.push(...res.data.rows)
      this.loading = false
      this.current++
      if (this.current > res.data.pageTotal) {
        this.finished = true
      }
    },
    hChange (sorter) {
      this.current = 1
      this.sorter = sorter
      this.list = []
      this.finished = false
      this.onLoad()
      this.loading = true
    }
  }
  // 因为页面刚加载时，就是在底部，会自动触发load事件，发请求，所以不需要在created中发请求
  // async created () {
  //   const res = await getArticle({
  //     current: 1,
  //     pageSize: 10,
  //     sorter: 'weight_desc'
  //   })
  //   this.list = res.data.rows
  //   console.log(this.list)
  // }
}
</script>

<style lang="less" scoped>
.article-page{
  margin-bottom: 50px;
  margin-top: 44px;
  .my-nav{
    height: 44px;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 999;
    background: #fff;
    display: flex;
    align-items: center;
    > a {
      color: #999;
      font-size: 14px;
      line-height: 44px;
      margin-left: 20px;
      position: relative;
      transition: all 0.3s;
      &::after {
        content: '';
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 0;
        width: 0;
        height: 2px;
        background: #222;
        transition: all 0.3s;
      }
      &.active {
        color: #222;
        &::after {
          width: 14px;
        }
      }
    }
    .logo{
      flex: 1;
      display: flex;
      justify-content: flex-end;
      > img{
        width: 64px;
        display: block;
        margin-right: 10px;
      }
    }
  }
}
</style>
